# -*- coding: utf-8 -*-
import base64
import time
from celery import task

from blueking.component.shortcuts import get_client_by_user

client = get_client_by_user("admin")
cmd = """
#!/bin/bash

MEMORY=$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')
DISK=$(df -h | awk '$NF=="/"{printf "%s", $5}')
CPU=$(top -bn1 | grep load | awk '{printf "%.2f%%", $(NF-2)}')
DATE=$(date "+%Y-%m-%d %H:%M:%S")
echo -e "$DATE|$MEMORY|$DISK|$CPU"
"""

@task()
def distribute_job(cmd="pwd", ip="10.0.2.63"):
    bk_biz_id = 2
    content = base64.b64encode(cmd)
    ip_list = [{"ip": ip, "bk_cloud_id": 0}]

    args = {"bk_biz_id": bk_biz_id,
            "ip_list": ip_list,
            "account": "root",
            "script_content": content}
    job_id = client.job.fast_exe_execute_script(args)['data']['job_instance_id']

    status_args = {"bk_biz_id": 2, "job_instance_id": job_id}
    while True:
        is_finished = client.job.get_job_job_instance_status(status_args)['data']['is_finished']
        if is_finished:
            break
        time.sleep(0.5)
    response = client.job.get_job_job_instance_log(status_args)
    return response['data'][0]['step_results'][0]['ip_logs'][0]['log_content']
